package com.wpml.netty.reactor;

import io.netty.channel.nio.NioEventLoopGroup;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.LinkedBlockingQueue;

public class SelectorThread extends Thread{

    Selector selector = null;

    LinkedBlockingQueue<Channel> queue = new LinkedBlockingQueue<>();

    SelectorThreadGroup stg;

    SelectorThread (SelectorThreadGroup stg) {
        try {
            selector = Selector.open();
            this.stg = stg;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void run() {

        while (true) {
            try {
//                System.out.println(Thread.currentThread().getName()+"   :  before select...."+ selector.keys().size());
                int nums = selector.select();
//                System.out.println(Thread.currentThread().getName()+"   :  after select...."+ selector.keys().size());
                if (nums > 0) {
                    Set<SelectionKey> keys = selector.selectedKeys();
                    Iterator<SelectionKey> iterator = keys.iterator();
                    while (iterator.hasNext()) {
                        SelectionKey key = iterator.next();
                        iterator.remove();
                        if (key.isAcceptable()) {
                            acceptHandler(key);
                        } else if (key.isReadable()) {
                            readHandler(key);
                        } else if (key.isWritable()) {

                        } else {
                            break;
                        }
                    }
                }

                if (!queue.isEmpty()) {
                    Channel c = queue.take();
                    if (c instanceof ServerSocketChannel) {
                        ServerSocketChannel server = (ServerSocketChannel) c;
                        server.register(selector, SelectionKey.OP_ACCEPT);

                        System.out.println(Thread.currentThread().getName() + " register listen");
                    } else if (c instanceof SocketChannel) {
                        SocketChannel client = (SocketChannel) c;
                        ByteBuffer buffer = ByteBuffer.allocateDirect(4096);
                        client.register(selector, SelectionKey.OP_READ, buffer);
                        System.out.println(Thread.currentThread().getName() + " register client: " + client.getRemoteAddress());
                    }
                }
            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
            }
        }


    }

    private void readHandler(SelectionKey key) {
        ByteBuffer buffer = (ByteBuffer) key.attachment();
        SocketChannel client = (SocketChannel) key.channel();
        buffer.clear();
        while (true) {
            try {
                // 数据读取到buffer中
                int num = client.read(buffer);
                if (num > 0) {
                    buffer.flip(); // 翻转
                    while (buffer.hasRemaining()) {
                        client.write(buffer);
                    }
                    buffer.clear();
                } else if (num == 0) {
                    break;
                } else {
                    // 客户端断开了
                    System.out.println("client : " + client.getRemoteAddress() + " 断开了......");
                    key.cancel();
                    break;
                }


            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void acceptHandler(SelectionKey key) {
        ServerSocketChannel server = (ServerSocketChannel) key.channel();
        try {
            SocketChannel client = server.accept();
            client.configureBlocking(false); // 设置非阻塞

            stg.nextSelector(client);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void setWorker(SelectorThreadGroup worker) {
        this.stg = worker;
    }
}
